package com.na.game.engine.graphics;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;

import com.na.game.engine.GameManager;
import com.na.game.engine.event.Updater;
import com.na.game.engine.resource.ResourceManager;
import com.na.game.engine.util.Util;
import com.na.game.engine.widget.Layout;

@Deprecated
public class Animation implements Updater, Painter {

	protected String name;
	// 这个动画包含的所有图片
	protected List<Image> images = new ArrayList<Image>();
	// 每张图片的坐标偏移
	protected List<int[]> pos = new ArrayList<int[]>();
	// 每张图片需要绘制的帧序列标记
	protected List<Integer> masks = new ArrayList<Integer>();
	// 当前帧数
	protected int tick;
	// 该动画大小
	protected int width, height;
	
	protected int x, y;
	
	protected String version = V_1_0;
	
	public static final String V_1_0 = "1.0";
	
	public Animation(String assetsXml) {
		this(null, assetsXml);
	}

	public Animation(Context context, String assetsXml) {
		try {
			Document doc = Util.getDoc(context, assetsXml);
			Element root = doc.getDocumentElement();
			version = root.getAttribute("version");
			String dir = root.getAttribute("dir");
			width = Integer.parseInt(root.getAttribute("width"));
			height = Integer.parseInt(root.getAttribute("height"));
			
			NodeList nodes = root.getElementsByTagName("image");
			for (int i = 0; i < nodes.getLength(); i++) {
				Element ele = (Element) nodes.item(i);
				Image image = GameManager.get(ResourceManager.class).getImageFromAssets(dir + ele.getAttribute("file"));
				int mask = Integer.parseInt(ele.getAttribute("mask"));
				int x = Integer.parseInt(ele.getAttribute("x"));
				int y = Integer.parseInt(ele.getAttribute("y"));
				
				images.add(image);
				masks.add(Integer.valueOf(mask));
				pos.add(new int[]{x, y});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void position(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	public int size() {
		return images.size();
	}
	
	@Override
	public void update() {
		if (++tick >= images.size()) {
			tick = 0;
		}
	}

	@Override
	public void paint(Graphics g) {
		g.setClip(x, y, width, height);
		int size = images.size();
		for (int i = 0; i < size; i++) {
			int mask = masks.get(i).intValue();
			if ((mask >> tick & 1) != 0) {
				int[] offset = pos.get(i);
				g.drawImage(images.get(i), x + offset[0], y + offset[1], Layout.TOP_LEFT);
			}
		}
	}
}
